package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.domain.CraftOperationDevice;
import com.uwlaser.domain.CraftOperationProduct;
import com.uwlaser.service.CraftOperationDeviceService;
import com.uwlaser.service.CraftOperationProductService;
import com.uwlaser.service.dto.CraftOperationProductQueryParam;
import com.uwlaser.service.mapper.CraftOperationProductMapper;
import com.uwlaser.utils.enums.DictValueEnum;
import lombok.AllArgsConstructor;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.domain.CraftOperation;
import com.uwlaser.service.CraftOperationService;
import com.uwlaser.service.dto.CraftOperationDto;
import com.uwlaser.service.dto.CraftOperationQueryParam;
import com.uwlaser.service.mapper.CraftOperationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import java.util.*;

/**
* @author zk-Qin
* @date 2022-05-11
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = CraftOperationService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CraftOperationServiceImpl extends CommonServiceImpl<CraftOperationMapper, CraftOperation> implements CraftOperationService {

    // private final RedisUtils redisUtils;
    private final CraftOperationMapper craftOperationMapper;

    private final CraftOperationProductService craftOperationProductService;

    private final CraftOperationDeviceService craftOperationDeviceService;

    @Override
    public PageInfo<CraftOperationDto> queryAll(CraftOperationQueryParam query, Pageable pageable) {
        IPage<CraftOperation> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<CraftOperation> page = craftOperationMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, CraftOperationDto.class);
    }

    @Override
    public List<CraftOperationDto> queryAll(CraftOperationQueryParam query){
        return ConvertUtil.convertList(craftOperationMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), CraftOperationDto.class);
    }

    @Override
    public CraftOperation getById(Integer id) {
        return craftOperationMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public CraftOperationDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), CraftOperationDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(CraftOperationDto resources) {
        CraftOperation entity = ConvertUtil.convert(resources, CraftOperation.class);
        CraftOperation craftOperation = new CraftOperation();
        craftOperation.setOperationCode(entity.getOperationCode());
        Integer integer = craftOperationMapper.selectCount(new QueryWrapper<>(craftOperation));
        if(integer > 0){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】已经存在，不能重复添加！");
        }

        if(resources.getProducts() == null || resources.getProducts().size() == 0){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】请选择应用于那些产品！");
        }

        if(resources.getDevices() == null || resources.getDevices().size() == 0){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】请选择关联设备！");
        }
        //添加产品关联关系
        craftOperationProductService.saveBatch(resources.getProducts());

        //添加设备关联关系
        craftOperationDeviceService.saveBatch(resources.getDevices());

        return craftOperationMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(CraftOperationDto resources){
        CraftOperation entity = ConvertUtil.convert(resources, CraftOperation.class);
        int ret = craftOperationMapper.updateById(entity);

        CraftOperation craftOperation = new CraftOperation();
        craftOperation.setOperationCode(entity.getOperationCode());
        Integer integer = craftOperationMapper.selectCount(new QueryWrapper<>(craftOperation));
        if(integer >= 2){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】已经存在，不能重复添加！");
        }

        if(resources.getProducts() == null || resources.getProducts().size() == 0){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】请选择应用于那些产品！");
        }

        if(resources.getDevices() == null || resources.getDevices().size() == 0){
            throw new RuntimeException("工序编号【"+entity.getOperationCode()+"】请选择关联设备！");
        }
        //先删除后插入
        deleteRelation(entity);

        //添加产品关联关系
        craftOperationProductService.saveBatch(resources.getProducts());

        //添加设备关联关系
        craftOperationDeviceService.saveBatch(resources.getDevices());

        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        // delCaches(ids);
        List<CraftOperation> craftOperations = craftOperationMapper.selectBatchIds(ids);
        for (CraftOperation entity : craftOperations) {
            deleteRelation(entity);
        }
        return craftOperationMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /**
     * 删除关联关系
     * @param entity
     */
    public void deleteRelation(CraftOperation entity){

        CraftOperationProduct craftOperationProduct = new CraftOperationProduct();
        craftOperationProduct.setOperationCode(entity.getOperationCode());
        craftOperationProductService.remove(new QueryWrapper<>(craftOperationProduct));

        CraftOperationDevice craftOperationDevice = new CraftOperationDevice();
        craftOperationDevice.setOperationCode(entity.getOperationCode());
        craftOperationDeviceService.remove(new QueryWrapper<>(craftOperationDevice));
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<CraftOperationDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (CraftOperationDto craftOperation : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("工序编号", craftOperation.getOperationCode());
              map.put("工序名称", craftOperation.getOperationName());
              map.put("工序类型", craftOperation.getOperationType());
              map.put("描述", craftOperation.getRemark());
              map.put("创建人", craftOperation.getCreateBy());
              map.put("创建时间", craftOperation.getCreateTime());
              map.put("更新人", craftOperation.getUpdateBy());
              map.put("更新时间", craftOperation.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
